package serializer

import (
	"bytes"
	"encoding/json"
	"errors"
)

var (
	// ErrNilPointer is returned when trying to decode into nil
	ErrNilPointer = errors.New("cannot decode into nil pointer")
)

// JSONSerializer implements the Serializer interface using JSON
type JSONSerializer struct{}

// NewJSONSerializer creates a new JSON serializer
func NewJSONSerializer() *JSONSerializer {
	return &JSONSerializer{}
}

// Encode encodes a Go object to JSON bytes
func (js *JSONSerializer) Encode(v interface{}) ([]byte, error) {
	return json.Marshal(v)
}

// Decode decodes JSON bytes to a Go object
func (js *JSONSerializer) Decode(data []byte, v interface{}) error {
	if v == nil {
		return ErrNilPointer
	}

	decoder := json.NewDecoder(bytes.NewReader(data))
	decoder.UseNumber()

	return decoder.Decode(v)
}

// ContentType returns the content type for JSON
func (js *JSONSerializer) ContentType() string {
	return "application/json"
}
